<style type="text/css" title="currentStyle">
	@import "../media/css/demo_table.css";
	@import "media/css/TableTools.css";
</style>

<script type="text/javascript" charset="utf-8" src="../media/js/jquery.dataTables.js"></script>
<script type="text/javascript" charset="utf-8" src="media/ZeroClipboard/ZeroClipboard.js"></script>
<script type="text/javascript" charset="utf-8" src="media/js/TableTools.js"></script>
<script type="text/javascript" charset="utf-8">
	$(document).ready( function () {
		/* You might need to set the sSwfPath! Something like:
		 *   TableToolsInit.sSwfPath = "/media/swf/ZeroClipboard.swf";
		 */
		$('#example').dataTable( {
			"sDom": 'T<"clear">lfrtip'
		} );
	} );
</script>

<?php
@set_time_limit(0);
function chk_folder($filename)
{ //echo $filename;
	$fp_load = @fopen($filename, "rb");
	if ( $fp_load )
	{ 
		return true;
	}
	else
	{ 
		return false;
	}
}
function getClosestElement($array, $value) 
{
	$size = count($array);
	$tmp = -1;
	if ($size > 0) 
	{
		//echo max($array)."<br><br>";
		//$ret = max($array);
		 while (list($key, $va) = each($array)) 
		 {			 
			 $diff = abs($va - $value);			
			 if($tmp == -1)
			 {
				 $tmp = $diff;
				 $k = $key;
				 //echo "1st ".$key." & ".$diff." = ".$value." diff ".$tmp."<br><br><br>";
				
			 }
			 else
			 {
				 //echo $key." & ".$diff." = ".$value." diff ".$tmp."<br>";
				 if($tmp > $diff) 
				 {
					 $tmp = $diff;
					 $k = $key;
				 }
			}
		}
		//echo "<br> ".$key." ".$va." & ".$diff." = ".$value." diff ".$tmp."<br>";
		return $k;
		//echo "<br><br>";
	}
	else 
	{
	  return NULL;
	}
	
}


function gpspathFunAll($date_offline,$deviceIMEI)
{
	$path1=DATAPATH.date('d-m-Y',strtotime($date_offline))."/".$deviceIMEI.".txt";
	
	if(chk_folder($path1))
	{
		  $file1 = @fopen($path1, "rb");
		if($file1)
		{
			$i=0;
			while(!feof($file1))
			{
			   $data1= fgets($file1);				 
			}
			 $data1 = getSortedData($data1);

			fclose($file1);
		}
		return $data1;
	}
		
}

function getFuel($data,$strtTime,$endliveime,$fuel_port,$fuel_params,$ent_val_mnt)
{
	//echo $ent_val_mnt;
	$timeArr= array();
	$strTime = '';
	$endTime = '';
	$count = 0;
	$tmpVal = 0;
	$tmpCount = -1;
	
	if(count($data)>0)
	{
		 $data1=explode("#",$data);
		 $j1 = 0;
	 //echo count($data1); 
	  while($j1 < count($data1))
	 {
		$data2=explode("@",$data1[$j1]);
		//echo '<pre>'; print_r($data2);echo '</pre>';
		if(count($data2)>1)
		{
			$data3=explode(",",$data2[1]);
			$vehi=$data3[0];
			$geodate = $data3[8]." ".$data3[9];
			$geoTime = date("H:i:s",strtotime($data3[9]));
			$curTime = explode(":",date("H:i:s",strtotime($data3[9])));
			$newTime  = (($curTime[0]) * 60) + $curTime[1];
			$curTime = (($curTime[0]) * 3600) + ($curTime[1]*60);
			 
			
			if($newTime  >= $strtTime && $newTime <=$endliveime)
			{
			if(!in_array($geoTime,$timeArr))
			{
				$fule_param = $data3[7]; 									
				$d = preg_split("/[\s,]+/",$fule_param);
				foreach($d as $e)
				{
					// echo substr($e,0,3).'<br>';
					if(substr($e,0,3)=='['.$fuel_port.'=')
					{
						  $v = str_replace(array('['.$fuel_port.'=',']'),'',$e); 
					}
				 }
				 
				if($tmpCount == -1 || $tmpCount == floor($curTime/$ent_val_mnt))
				{
					$tmpCount = floor($curTime/$ent_val_mnt);
					
					if($count == 0)
						$strTime = $geoTime;										
					//echo strlen($v).' '.$strTime.' '.$endTime;
					
					if(strlen($v) > 3 && $strTime != '' && $endTime == '')
					{
						$v = $v/1000;
						$tmpVal += getClosestElement($fuel_params,$v);
						//$altData [] = getClosestElement($fuel_params,$v).",".date("h:i:s A",strtotime($data3[9])).",".$data3[8];
					}					
					$count++;
				}
				elseif($strTime != '')
				{
					$endTime = $geoTime;
					if(strlen($v) > 3)
					{
						$v = $v/1000;
						$tmpVal += getClosestElement($fuel_params,$v);
						//$altData [] = getClosestElement($fuel_params,$v).",".date("h:i:s A",strtotime($data3[9])).",".$data3[8];
					}
					$count++;
				}
				if($strTime != '' && $endTime != '')
				{
					//echo "<br>".$tmpVal.' '.$count."<br>";
					$tmpVal = round($tmpVal / $count);
					$altData [] = $tmpVal.",".date("h:i:s A",strtotime($data3[9])).",".$data3[8].",".$strTime.",".$endTime;
					//echo "<br>";
					$tmpCount = -1;
					$tmpVal = 0;
					$strTime = '';
					$endTime = '';
					$count = 0;
				}
			}
			}
		 }
		
		$j1++;
	}
	}
	//echo implode("#",$altData)."<br>";
	if(count($altData) > 0)
		return implode("#",$altData);
	else 
		return "";
}


if($recordUserInfo[ci_clientType] == "Client" && $recordUserInfo[ui_isAdmin] == "1")
{
	$devices_query =  "SELECT * FROM tb_deviceinfo,tb_client_subscription WHERE tcs_isActive = 1 AND tcs_deviceId = di_id AND di_clientId =".$_SESSION[clientID]." AND di_status = 1 ORDER BY di_deviceName,di_deviceId ASC";
}
else if($recordUserInfo[ci_clientType] == "Client" && $recordUserInfo[ui_isAdmin] == "0" && $recordUserInfo[ui_roleId] == "1")
{
	$devices_query = "SELECT * FROM tb_deviceinfo,tb_client_subscription WHERE tcs_isActive = 1 AND tcs_deviceId = di_id AND di_status = 1 AND di_clientId=".$_SESSION[clientID]." AND di_assignedUserId = ".$_SESSION[userID]." ORDER BY di_deviceName,di_deviceId ASC";
}

$devices_resp = mysql_query($devices_query);	


?>
<script type="text/javascript" language="javascript">


function validateMapReport()
{
  if(document.getElementById('map_device_id').value== 0 )
  { alert("Select Vehicle");  document.getElementById('map_device_id').focus();  return 0;  }
  
  if(document.getElementById('from_date').value=='')
  { alert("Select From Date"); document.getElementById('from_date').focus();  return 0;  }
  
  if(document.getElementById('to_date').value=='')
  { alert("Select To Date");  document.getElementById('to_date').focus(); return 0; }
  
       var t1=document.getElementById('from_date').value ;
        var t2=document.getElementById('to_date').value;

        var one_day=1000*60*60*24; 
		var x=t1.split("-");     
        var y=t2.split("-");
        var date1=new Date(x[2],(x[1]-1),x[0]);
  
        var date2=new Date(y[2],(y[1]-1),y[0]);
        var month1=x[1]-1;
        var month2=y[1]-1;
        var diff=Math.ceil((date2.getTime()-date1.getTime())/(one_day)); 
         
		 if(diff < 0){
       alert("From Date should be prior to To Date."); document.getElementById('to_date').select();return 0;

		 }
	return 1;
	
}
function sendCSVData()
{
  document.frmKiloData.submit();
}

function showPreloader()
{
	var returnVal = validateMapReport()
	if(returnVal == 1)
	{

		document.getElementById('popup_div').innerHTML = '<div id="loading_txt" >Loading...</div>';
		document.frm_map_filter.submit();
	}
}
function showFormDiv()
{
	if(document.getElementById('formDiv').style.display=='none')
	{
		document.getElementById('formDiv').style.display = 'block';
		document.getElementById('shLink').innerHTML = "Hide Form";
	}
	else
	{
		document.getElementById('formDiv').style.display = 'none';
		if(document.getElementById('shLink'))
		document.getElementById('shLink').innerHTML = "Show Form";
	}
}
function hidePreLoader()
{
	document.getElementById('popup_div').innerHTML = '&nbsp;';

}
jQuery(function() {

    //$("#time3, #time4").timePicker();
	 $("#time3, #time4").timePicker({
	  startTime: "12:01 AM", // Using string. Can take string or Date object.
	  endTime: "11:59 PM", // Using Date object here.
	  show24Hours: false,
	  separator: ':',
	  step: 1});    
        
    // Store time used by duration.
    var oldTime = $.timePicker("#time3").getTime();
    
    // Keep the duration between the two inputs.
    $("#time3").change(function() {
      if ($("#time4").val()) { // Only update when second input has a value.
        // Calculate duration.
        var duration = ($.timePicker("#time4").getTime() - oldTime);
        var time = $.timePicker("#time3").getTime();
        // Calculate and update the time in the second input.
        $.timePicker("#time4").setTime(new Date(new Date(time.getTime() + duration)));
        oldTime = time;
      }
    });
    // Validate.
    $("#time4").change(function() {
      if($.timePicker("#time3").getTime() > $.timePicker(this).getTime()) {
        $(this).addClass("error");
      }
      else {
        $(this).removeClass("error");
      }
    });
});
var minVal;
var m1 = '<?php if($_POST[selDuration]) echo $_POST[selDuration]; else echo 5;?>';
for(k=1; k <= 30; k++)
{
	if(k == m1)
	{
		minVal +='<option value='+k+' selected="selected">'+k+' Min</option>';
	}
	else
	{
		minVal +='<option value='+k+'>'+k+' Min</option>';
	}
}
$(function() {
	$( "#from_date" ).datepicker({
		changeMonth: true,
		changeYear: true,
		maxDate: 0,
		showOn: "button",
		buttonImage: "images/calendar.gif",
		buttonImageOnly: true,
		dateFormat : "dd-mm-yy"
	});
});
$(function() {
	$( "#to_date" ).datepicker({
		changeMonth: true,
		changeYear: true,
		maxDate: 0,
		showOn: "button",
		buttonImage: "images/calendar.gif",
		buttonImageOnly: true,
		dateFormat : "dd-mm-yy"
	});
});

</script>
<div id="formDiv">
<form id="frm_map_filter" name="frm_map_filter" method="post" action="" onsubmit="return validateMapReport();"> 
<table class="gridform_final" style="width:75%">
<tr><th colspan="4">Fuel Report</th></tr>
  <tr>
    <td width="15%" align="right"><span class="form_text">Select Device</span></td>
    <td width="35%" align="left">
        <select name="map_device_id" id="map_device_id" class="hours_select" tabindex="1" style="width:80%;" onchange="document.frm_map_filter.txtVehicleName.value = this.options[selectedIndex].text">
        <option value="0">Select Device</option>
        <?php 
        while($devices_fetch = @mysql_fetch_assoc($devices_resp)) 
        {
			$renewDate = date("d-m-Y",strtotime("-1 days ".$devices_fetch[tcs_renewalDateTo]));
			//echo $date_offline." <= ".date("d-m-Y",strtotime($renewDate))."<br>";
			if(strtotime(date('d-m-Y')) <= strtotime($renewDate))
			{
			if($devices_fetch[di_deviceName])
				$devName = $devices_fetch[di_deviceName];
			else
				$devName = $devices_fetch[di_deviceId];
        ?>
        <option value="<?php echo $devices_fetch[di_imeiId]; ?>" 
        <?php if($_POST[map_device_id] == $devices_fetch[di_imeiId]) echo "selected"; ?>><?php echo $devName; ?></option>
        <?php } } ?>	
        </select>
        <input type="hidden" name="txtVehicleName" id="txtVehicleName" />
        <input type="hidden" name="curdate" id="curdate" value="<?php echo date('Y-m-d'); ?>" />
    </td>
    <td align="right" width="15%"><span class="form_text">Duration</span></td>
    <td align="left" width="35%">
        <select id="selDuration" name="selDuration">
			<script language="javascript">
				document.write(minVal);
            </script>
        </select>
    </td>
    </tr>              
    <tr>
    <td width="15%" align="right"><span class="form_text">From Date & Time</span></td>
    <td width="35%" align="left">
    <input type="text" name="from_date" id="from_date" readonly="true" tabindex="3" size="12" value="<?php if(isset($_POST[from_date])) echo $_POST[from_date]; else echo date("d-m-Y"); ?>" style="width:140px;"/>&nbsp;
    <span><input type="text" name="time3" readonly="true" id="time3" size="7" tabindex="4" value="<?php if($_POST[time3]) echo $_POST[time3]; else echo "12:01 AM";?>" /></span>
    </td>
    <td width="15%" align="right"><span class="form_text">To Date & Time</span></td>
    <td width="35%">
    <input type="text" name="to_date" id="to_date" size="12" style="width:140px;" tabindex="5" readonly="true" value="<?php if(isset($_POST[to_date])) echo $_POST[to_date]; else echo date("d-m-Y"); ?>" />&nbsp;
    <span><input type="text" name="time4" readonly="true" id="time4" size="7" tabindex="6" value="<?php if($_POST[time4]) echo $_POST[time4]; else echo "11:59 PM";?>" /></span>
    </td>
  </tr>
<!--
  <tr>
    <td align="right" width="15%"><span class="form_text"></span></td>
    <td align="left" width="35%" colspan="3">
        
        <input type="radio" <?php if(isset($_POST[formula]) && $_POST[formula]=="avgval"){echo 'checked';}?> value="avgval" id="formula" name="formula">Take avg value
		 <input type="radio" <?php if(isset($_POST[formula]) && $_POST[formula]=="formula"){echo 'checked';}?> value="formula" id="formula" name="formula">Use formula
		<input type="radio" <?php if(isset($_POST[formula]) && $_POST[formula]=="chart"){echo 'checked';}?> value="chart" id="formula" name="formula">Use chart
    </td>
    </tr> 
 <tr>
    <td width="15%" align="right"><span class="form_text">Omit Exceeded Voltages</span></td>
    <td width="35%" align="left" colspan="3">
        <input type="checkbox" value="1" id="exceed_vol" name="exceed_vol"
		<?php if($_POST[exceed_vol]=='1'){echo 'checked';}?>
    </td>
    </tr>-->       
  <tr>
    <td height="33" colspan="4" style="text-align:center">
    <input type="button" name="map_filter_btn"   value="Filter" class="save_btn" tabindex="6"  onclick="showPreloader();"/>
    <input type="hidden" name="map_filter_btn" value="Filter" />
    <input type="button" name="map_cancel_btn" id="map_cancel_btn" value="Reset" class="save_btn" onclick="location.href='index.php?ch=fuel';" tabindex="7" /> 
    </td>
  </tr>
</table>
</form>
</div>
<div id="popup_div" style=" display:block; border:0px;" >

</div>	

<?php
if(isset($_POST[map_filter_btn]) && $_POST[map_filter_btn]!='')
{ 
	//echo '<pre>'; print_r($_POST);echo '</pre>';
	$sdate = $_POST[from_date];
	$edate = $_POST[to_date];
	
	$strtTime = explode(":",date("H:i",strtotime($_POST[time3])));
	$strtTime = (($strtTime[0] * 60) + $strtTime[1]);
	
	$endTime = explode(":",date("H:i",strtotime($_POST[time4])));
	$endTime = (($endTime[0] * 60) + $endTime[1]);
	
	$ent_val_mnt = $_POST[selDuration]*60;
/********End Full tank filled status*********************/

$fuel_sql ="select * from tb_fuel where imei=".$_POST[map_device_id]." order by id asc";
$fuel_rows = $db->query($fuel_sql);
$k=0;
while($fuel_result = @mysql_fetch_assoc($fuel_rows)){
	 $fuel_params[$fuel_result[tanksize]] = $fuel_result[voltage];
	 $k++;
}


$fuel_info_query =  "SELECT * FROM tb_deviceinfo,tb_client_subscription WHERE tcs_isActive = 1 AND tcs_deviceId = di_id AND di_imeiId =".$_POST[map_device_id]." AND di_status = 1";
$fuel_info_resp = mysql_query($fuel_info_query);	
while($fuel_info_fetch = @mysql_fetch_assoc($fuel_info_resp)) 
{	
	$fuel_port = $fuel_info_fetch[di_Fuelport];	
}

if($_POST[from_date] == $_POST[to_date])
{
	$data =  gpspathFunAll($_POST[from_date],$_POST[map_device_id]);		
	$finData = getFuel($data,$strtTime,$endTime,$fuel_port,$fuel_params,$ent_val_mnt);
	//$finData[] = array(date('d-m-Y',strtotime($_POST[from_date]))=>$data);
}
else
{
	$z = GetDays($sdate, $edate);
	for($y=0; $y<count($z); $y++)
	{ 
		if($y == 0) 
		{
			$strtTime1 = $strtTime;
			$endTime1 = 1439;
			$data =  gpspathFunAll($z[$y],$_POST[map_device_id]);	
			$res1 = getFuel($data,$strtTime1,$endTime1,$fuel_port,$fuel_params,$ent_val_mnt);
			if($res1)		
			$finData[]= $res1;	
			//$finData[] = array(date('d-m-Y',strtotime($z[$y]))=>$data);
		}
		elseif($y == count($z)-1) 
		{
			$strtTime1 = 0;
			$endTime1 = $endTime;
			$data =  gpspathFunAll($z[$y],$_POST[map_device_id]);		
			$res2= getFuel($data,$strtTime1,$endTime1,$fuel_port,$fuel_params,$ent_val_mnt);
			if($res2)		
			$finData[]= $res2;	
			//$finData[] = array(date('d-m-Y',strtotime($z[$y]))=>$data);
		}
		elseif($y < count($z)-1) 
		{
			$strtTime1 = 0;
			$endTime1 = 1439;
			$data =  gpspathFunAll($z[$y],$_POST[map_device_id]);			
			$res3 = getFuel($data,$strtTime1,$endTime1,$fuel_port,$fuel_params,$ent_val_mnt);
			if($res3)		
			$finData[]= $res3;
			//$finData[] = array(date('d-m-Y',strtotime($z[$y]))=>$data);
		}
	}
	$finData = implode("#",$finData);
}
?>
<div class="listofusers" align="right">&nbsp;<a href="#" class="error_strings" id="shLink" onClick="showFormDiv();">Show Form</a></div>
<div style="overflow-Y:hidden; padding-top:2%">
<table cellpadding="0" cellspacing="0" border="0" class="gridform_final" id="example">   
<thead>
	<tr>
    	<th width="2%">#</th>
	  	<th width="10%">Date (dd-mm-yy) </th>
        <th width="30%">Device Name</th>
        <th width="30%">Time (12 hours format)</th>
        <th width="30%">Fuel (Ltrs)</th>   		
     </tr>
  </thead>
  <tbody>
      
<?php
	//print_r($finData);
//	exit;
	if(count($finData) > 0)
	{
			$tTdiff1 = explode("#",$finData);
			//print_r($tTdiff1); //exit;
			for($k=0;$k<count($tTdiff1)-1;$k++)
			{
			$tTdiff = explode(",",$tTdiff1[$k]);
			//print_r($tTdiff); exit;
			?>		
			 <tr <?php if($r % 2 == 0) { echo 'class="odd_row"';} else { echo 'class="even_row"'; } ?> >
			   <td valign="top"><?php echo $k+1; ?></td>
			   <td valign="top"><?php echo date('d-m-Y',strtotime($tTdiff[2])); ?></td>
			   <td valign="top"><?php echo $_POST[txtVehicleName]; ?></td>
			   <td valign="top"><?php echo $tTdiff[1]; ?></td>
			   <td valign="top"><?php echo $tTdiff[0]; ?></td>
             </tr>
			   <?php 
			}
	}
	else
	{
		echo '<tr><td colspan="5" align="center">No Records Found</td></tr>'; 

	}
	
?>
</tbody>
</table>
</div>
<script type="text/javascript">
showFormDiv();
hidePreLoader();
</script>
<?php 
}
?> 
